from flask import Flask, request
from flask import jsonify
import pymongo
from t66y import settings

app = Flask(__name__, static_folder="d:/images/")
app.config["JSON_AS_ASCII"] = False

mongo_client = pymongo.MongoClient(host='127.0.0.1', port=27017)
collection = mongo_client.t66y.article

@app.route("/<int:page>/<int:size>")
def hello_world(page, size):
    if page == 0:
        page = 1
    page = page - 1
    print(page)
    print(size)
    records = collection.find({"$and":[{"favorite": {"$ne": True}}, {"status": {"$ne": 0}}, {"status": {"$ne": 1}}, {"status": {"$ne": 2}}]}).limit(size).sort("index", -1).skip(page * size)
    data = []
    for item in records:
        data_imgs = []
        dict.setdefault(item, 'status', -1)
        for article in item["details"]:
            imgs = article.get("imgs")
            if not imgs:
                continue
            for img in imgs:
                if settings.not_trash_img(img):
                    data_imgs.append(
                        "http://192.168.0.112/images/" + item["time"] + "/" + str(item["index"]) + "/" + img.split('/')[
                            -1])
        dict.setdefault(item, "favorite", False)
        print(type(item["index"]))
        data.append({
            "title": item["title"],
            "time": item["time"],
            "url": item["url"],
            "author": item["author"],
            "index": item["index"],
            "images": data_imgs,
            "favorite": item["favorite"],
            "status": item["status"]
        })
    print(data)
    return jsonify(data)


@app.route("/post/<int:index>", methods=['get'])
def post(index):
    item = collection.find_one({"index": index})
    if item:
        print(item)
        dict.setdefault(item, 'status', -1)
        data_imgs = []
        for article in item["details"]:
            imgs = article.get("imgs")
            if not imgs:
                continue
            for img in imgs:
                if settings.not_trash_img(img):
                    data_imgs.append(
                        "http://192.168.0.112/images/" + item["time"] + "/" + str(item["index"]) + "/" + img.split('/')[
                            -1])
        dict.setdefault(item, "favorite", False)
        print(type(item["index"]))
        return jsonify({
            "title": item["title"],
            "time": item["time"],
            "url": item["url"],
            "author": item["author"],
            "index": item["index"],
            "images": data_imgs,
            "favorite": item["favorite"],
            "status": item["status"]
        })
    else:
        return jsonify({"code": -1, "msg": "no flag or type wrong"})

@app.route("/favorite", methods=['POST'])
def favorite():
    index = request.get_json().get('index')
    flag = request.get_json().get('flag')
    print(index)

    print(flag)

    record = collection.find_one({"index": index})
    if flag and type(flag) == bool:
        print(record)
        collection.update_one({"index": index}, {"$set": {"favorite": True}})
        return jsonify({"code": 0})
    else:
        return jsonify({"code": -1, "msg": "no flag or type wrong"})


@app.route("/favorites/<int:page>/<int:size>", methods=['GET'])
def favorites(page, size):
    if page == 0:
        page = 1
    page = page - 1
    records = collection.find({"favorite": True}).limit(size).sort("index", -1).skip(page * size)
    data = []
    for item in records:
        data_imgs = []
        dict.setdefault(item, 'status', -1)
        for article in item["details"]:
            imgs = article.get("imgs")
            if not imgs:
                continue
            for img in imgs:
                if settings.not_trash_img(img):
                    data_imgs.append(
                        "http://192.168.0.112/images/" + item["time"] + "/" + str(item["index"]) + "/" + img.split('/')[
                            -1])
        data.append({
            "title": item["title"],
            "time": item["time"],
            "url": item["url"],
            "author": item["author"],
            "index": item["index"],
            "images": data_imgs,
            "favorite": item["favorite"],
            "status": item["status"]
        })
        print(data)
    return jsonify(data)

@app.route("/setStatus", methods=['POST'])
def set_status():
    index = request.get_json().get('index')
    status = request.get_json().get('status')
    print(status)

    record = collection.find_one({"index": index})
    if record:
        print(record)
        collection.update_one({"index": index}, {"$set": {"status": status}})
        return jsonify({"code": 0})
    else:
        return jsonify({"code": -1, "msg": "no flag or type wrong"})


@app.route("/getStatus/<int:status>/<int:page>/<int:size>", methods=['GET'])
def get_status(status, page, size):
    print(status)
    print(page)
    print(size)
    if page == 0:
        page = 1
    page = page - 1
    records = collection.find({"status": status}).limit(size).sort("index", -1).skip(page * size)
    data = []
    for item in records:
        dict.setdefault(item, 'status', -1)
        dict.setdefault(item, 'favorite', False)
        data_imgs = []
        for article in item["details"]:
            imgs = article.get("imgs")
            if not imgs:
                continue
            for img in imgs:
                if settings.not_trash_img(img):
                    data_imgs.append(
                        "http://192.168.0.112/images/" + item["time"] + "/" + str(item["index"]) + "/" + img.split('/')[
                            -1])
        data.append({
            "title": item["title"],
            "time": item["time"],
            "url": item["url"],
            "author": item["author"],
            "index": item["index"],
            "images": data_imgs,
            "favorite": item["favorite"],
            "status": item["status"]
        })
    print(data)
    return jsonify(data)


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
